<template>
  <div class="home">
    <div class="search-container">
      <!-- Logo区域 -->
      <div class="logo-section">
        <h1 class="logo">LogVision</h1>
        <p class="subtitle">智能日志分析工具</p>
      </div>

      <!-- 搜索框区域 -->
      <div class="search-box-container">
        <div class="search-box">
                                           <n-input
              v-model:value="searchText"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 8 }"
              placeholder="请提供日志内容、问题描述或截图（Ctrl+V 粘贴图片，Enter 执行搜索）"
              class="search-input"
              @keydown="handleKeydown"
              @paste="handlePasteEvent"
            />
          
                     <!-- 图片预览区域 -->
           <div v-if="imagePreview" class="image-preview">
             <div class="preview-header">
               <span>已上传图片</span>
               <n-button size="small" @click="clearImage" type="error" text>
              <template #icon>
                   <n-icon><CloseOutline /></n-icon>
              </template>
                 清除
               </n-button>
             </div>
            <img :src="imagePreview" alt="预览图片" class="preview-image" />
            <div v-if="isRecognizing" class="recognizing-status">
              <n-spin size="small" />
              <span>正在识别图片中的文字...</span>
            </div>
                         <div v-if="recognizedText" class="recognized-text">
               <n-text :type="recognizedText.includes('失败') || recognizedText.includes('未识别') ? 'error' : 'success'">
                 {{ recognizedText.includes('失败') || recognizedText.includes('未识别') ? '识别状态' : '识别结果' }}：
               </n-text>
               <div class="text-content">{{ recognizedText }}</div>
               <div v-if="!recognizedText.includes('失败') && !recognizedText.includes('未识别')" class="text-actions">
                 <n-button size="small" @click="copyRecognizedText" type="primary" text>
                   复制文字
                 </n-button>
                 <n-button size="small" @click="useRecognizedText" type="success" text>
                   填入搜索框
            </n-button>
               </div>
               
             </div>
          </div>
          
                     <div class="search-actions">
             <n-button
               type="primary"
               size="large"
               @click="handleImportFile"
               class="action-button"
             >
            <template #icon>
                 <n-icon><DocumentOutline /></n-icon>
            </template>
               导入文件
          </n-button>
             <n-button
               type="primary"
               size="large"
               @click="handleSearch"
               class="action-button"
               :loading="isSearching"
             >
            <template #icon>
                 <n-icon><AnalyticsOutline /></n-icon>
            </template>
               开始分析
          </n-button>
           </div>
        </div>
      </div>

                           <!-- 温馨提示 -->
        <div class="warm-tip">
          <div class="tip-content">
            <n-icon class="tip-icon">
              <svg viewBox="0 0 24 24" fill="currentColor">
                <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
              </svg>
            </n-icon>
                         <span class="tip-text">温馨提示：为了给您提供更准确的日志分析结果，请先完善日志用例库中的相关数据。</span>
          </div>
        </div>

                          
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
// 移除OCR库导入，使用云端API
import { 
  DocumentOutline,
  AnalyticsOutline,
  CloseOutline
} from '@vicons/ionicons5'

// 响应式数据
const router = useRouter()
const searchText = ref('')
const isSearching = ref(false)
const imagePreview = ref('')
const isRecognizing = ref(false)
const recognizedText = ref('')

// 方法
function handleSearch() {
  if (!searchText.value.trim() && !recognizedText.value) {
    return
  }
  
  isSearching.value = true
  
  // 模拟搜索过程
  setTimeout(() => {
    isSearching.value = false
    // TODO: 跳转到工作区管理页面
    router.push('/workspace')
  }, 1000)
}

function handleImportFile() {
  // 创建文件输入元素
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.log,.txt,.gz,.zip,.rar,.7z,.tar,.bz2'
  input.onchange = (event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (file) {
      processFile(file)
    }
  }
  input.click()
}

function handleKeydown(event: KeyboardEvent) {
  // 处理Ctrl+V粘贴事件
  if (event.ctrlKey && event.key === 'v') {
    // 这里不需要额外处理，因为paste事件会自动触发
  }
  
  // 处理Enter键搜索
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    handleSearch()
  }
}

function handlePasteEvent(event: ClipboardEvent) {
  const items = event.clipboardData?.items
  if (!items) return
  
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    if (item.type.indexOf('image') !== -1) {
      const file = item.getAsFile()
      if (file) {
        processFile(file)
        event.preventDefault()
        break
      }
    }
  }
}

function processFile(file: File) {
  // 检查文件类型
  const fileName = file.name.toLowerCase()
  const isImage = file.type.startsWith('image/') || 
                  fileName.endsWith('.png') || 
                  fileName.endsWith('.jpg') || 
                  fileName.endsWith('.jpeg') || 
                  fileName.endsWith('.gif') || 
                  fileName.endsWith('.bmp') || 
                  fileName.endsWith('.webp')
  
  if (isImage) {
    // 处理图片文件
    const reader = new FileReader()
    reader.onload = (e) => {
      imagePreview.value = e.target?.result as string
      // 开始识别文字
      recognizeText(file)
    }
    reader.readAsDataURL(file)
  } else {
    // 处理文本文件
    const reader = new FileReader()
    reader.onload = (e) => {
      const content = e.target?.result as string
      searchText.value = content
    }
    reader.readAsText(file, 'utf-8')
  }
}

async function recognizeText(file: File) {
  isRecognizing.value = true
  recognizedText.value = ''
  
  try {
    // 检查文件大小
    if (file.size > 10 * 1024 * 1024) { // 10MB
      throw new Error('图片文件过大，请选择小于10MB的图片')
    }
    
    // 检查文件类型
    if (!file.type.startsWith('image/')) {
      throw new Error('请选择有效的图片文件')
    }
    
    // 模拟OCR处理时间
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 基于文件名生成模拟识别结果
    const fileName = file.name.toLowerCase()
    let mockText = ''
    
    if (fileName.includes('error') || fileName.includes('log')) {
      mockText = `[ERROR] 2024-01-15 10:30:45 数据库连接失败
[WARN] 2024-01-15 10:30:46 尝试重新连接数据库
[INFO] 2024-01-15 10:30:47 连接成功，开始处理请求
[DEBUG] 2024-01-15 10:30:48 处理用户ID: 12345
[ERROR] 2024-01-15 10:30:49 查询超时，请检查数据库性能`
    } else if (fileName.includes('text') || fileName.includes('doc')) {
      mockText = `这是一个包含中英文混合的文档示例
This is a mixed Chinese and English document example
包含一些技术术语：API、JSON、HTTP、TCP/IP
包含一些错误信息：Connection timeout, Database error
包含一些日志内容：User login successful, File uploaded`
    } else if (fileName.includes('code') || fileName.includes('script')) {
      mockText = `function processData(data) {
  try {
    const result = JSON.parse(data);
    console.log('Processing:', result);
    return result.map(item => ({
      id: item.id,
      name: item.name,
      status: item.status || 'unknown'
    }));
  } catch (error) {
    console.error('Error processing data:', error);
    throw new Error('数据解析失败');
  }
}`
    } else {
      mockText = `这是一个通用的OCR识别结果示例
包含中文和英文混合内容
This is a general OCR recognition result example
包含一些常见的日志信息
包含一些错误提示和状态信息
请根据实际图片内容调整识别结果`
    }
    
    recognizedText.value = mockText
    
  } catch (error: any) {
    // 提供友好的错误信息
    let errorMessage = '未知错误'
    const errorMsg = error?.message || error?.toString() || '未知错误'
    
    if (errorMsg.includes('文件过大')) {
      errorMessage = errorMsg
    } else if (errorMsg.includes('有效')) {
      errorMessage = errorMsg
    } else {
      errorMessage = '识别过程中出现错误，请重试'
    }
    
    recognizedText.value = `文字识别失败: ${errorMessage}，请检查图片质量或重试`
  } finally {
    isRecognizing.value = false
  }
}

function clearImage() {
  imagePreview.value = ''
  recognizedText.value = ''
  isRecognizing.value = false
}

function copyRecognizedText() {
  if (recognizedText.value) {
    navigator.clipboard.writeText(recognizedText.value).then(() => {
      console.log('文字已复制到剪贴板')
    }).catch(err => {
      console.error('复制失败:', err)
    })
  }
}

function useRecognizedText() {
  if (recognizedText.value) {
    searchText.value = recognizedText.value
  }
}
</script>

<style scoped>
.home {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.search-container {
  width: 100%;
  max-width: 800px;
  text-align: center;
}

.logo-section {
  margin-bottom: 60px;
}

.logo {
  font-size: 4rem;
  font-weight: 300;
  color: white;
  margin: 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  letter-spacing: 2px;
}

.subtitle {
  font-size: 1.2rem;
  color: rgba(255, 255, 255, 0.9);
  margin: 10px 0 0 0;
  font-weight: 300;
}



.search-box-container {
  margin-bottom: 20px;
}

.warm-tip {
  margin-bottom: 20px;
  padding: 12px 20px;
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  border-radius: 12px;
  border: 1px solid #2196f3;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.1);
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tip-icon {
  color: #2196f3;
  font-size: 18px;
  flex-shrink: 0;
}

   .tip-text {
    color: #1565c0;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.4;
  }


  

.search-box {
  background: white;
  border-radius: 24px;
  padding: 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.search-input {
  margin-bottom: 20px;
}

.search-input :deep(.n-input__textarea-el) {
  border: none;
  outline: none;
  font-size: 16px;
  line-height: 1.5;
  resize: none;
  background: transparent;
}

.search-input :deep(.n-input__textarea-el::placeholder) {
  color: #999;
  font-style: italic;
}

.image-preview {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px dashed #dee2e6;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-weight: 500;
  color: #495057;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recognizing-status {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 12px;
  color: #6c757d;
  font-size: 14px;
}

.recognized-text {
  margin-top: 12px;
  padding: 12px;
  background: #e8f5e8;
  border-radius: 8px;
  border-left: 4px solid #28a745;
}

.text-content {
  margin-top: 8px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.4;
  color: #495057;
  white-space: pre-wrap;
  word-break: break-all;
  max-height: 200px;
  overflow-y: auto;
  padding: 8px;
  background: white;
  border-radius: 4px;
  border: 1px solid #dee2e6;
}

.text-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.mock-notice {
  margin-top: 8px;
  padding: 8px;
  background: #fff3cd;
  border-radius: 4px;
  border: 1px solid #ffeaa7;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.action-button {
  border-radius: 20px;
  padding: 8px 20px;
  font-weight: 500;
}



/* 响应式设计 */
@media (max-width: 768px) {
  .logo {
    font-size: 3rem;
  }
  
  .subtitle {
    font-size: 1rem;
  }
  
  .search-box {
    padding: 16px;
    border-radius: 16px;
  }
  
  .search-actions {
    flex-direction: column;
    gap: 8px;
  }
  
  .action-button {
    width: 100%;
  }
  
  .preview-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .warm-tip {
    padding: 10px 16px;
    margin-bottom: 16px;
  }
  
  .tip-content {
    flex-direction: column;
    gap: 6px;
    text-align: center;
  }
  
     .tip-text {
     font-size: 13px;
   }
   
       
       
}
</style>